﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using SlaughterItem.Common.Domains.Check_Ins;
using SlaughterItem.Common.Domains.ListWeek2;
using SlaughterItem.Common.Domains.UPCTable;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace GetSlaughterItem.API.Application.Commands.Week02.BasicSettings
{
    public class TareSuretenHandler : IRequestHandler<TareSuretenCommend, Result>
    {
        private readonly IBaseRepositoryGet<Tare> Tare;
        private readonly IBaseRepositoryGet<UPCData> UPCData;

        public TareSuretenHandler(IBaseRepositoryGet<Tare> Tare, IBaseRepositoryGet<UPCData> UPCData)
        {
            this.Tare = Tare;
            this.UPCData = UPCData;
        }

        public async Task<Result> Handle(TareSuretenCommend request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var list = (from a in Tare.GetAll()
                           join b in UPCData.GetAll() on a.GoodsMinuteId equals b.GoodsMinuteId
                           where a.IsDelete == false
                           select new
                           {
                               a.TareId,
                               a.TareMeasure,
                               a.TareStandardWeight,
                               a.TareStatus,
                               a.TareRemark,
                               a.IsDisable,
                               a.IsDelete,
                               b.GoodsMinuteId,
                               b.UPCDataName,
                           }).ToList();

                if (request.GoodsMinuteId > 0)
                {
                    list = list.Where(x => x.GoodsMinuteId == request.GoodsMinuteId).ToList();
                }

                if (request.TareStatus != null)
                {
                    list = list.Where(x => x.TareStatus == request.TareStatus).ToList();
                }

                var totalCount = list.Count;
                var pagecount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
                list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                var info = new
                {
                    totalCount,
                    pagecount,
                    list,
                };

                if (list != null)
                {
                    result.Code=(int)CommonErrorCode.Success;
                    result.Data = info;
                    result.Msg = "成功";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
